package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

/**
 * http://www.emoney.cn/ 益盟操盘手
 *  abc
 */
public class EmoneyNewsAnalyse implements AnalyseNews{
	
	public boolean isDetailPage(String url) {
		boolean bRet=false;
		String[] regex={
				"http://news.emoney.cn/n_[0-9]*_dms[0-9]*_[0-9]*.shtml",
				"http://news.emoney.cn/n_[0-9]*_[0-9]*_[0-9]*.shtml",
				"http://news.emoney.cn/[a-z]*/[0-9]*.shtml"
				};
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {		
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}		
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();		
		if(!isDetailPage(url)){
		}				
		news.setUrl(url);
		
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		String dateStr=null;
		Document doc=Jsoup.parse(htmltxt);

		title =doc.select("h3").text();
		if (StringUtils.isBlank(title)) {
			title=doc.select("h1").text();
		}
		
		dateStr=doc.select(".source").text();
		if(StringUtils.isBlank(dateStr)) {
			dateStr=doc.select(".RL_details_time span").text();
		}
		
		content=HtmlCleaner.getContentHtml(url,doc.select(".RL_details_content p"));

		/*
		 * 作者
		 */
		String authorStr=null;
		authorStr=doc.select("div.info div.p1").text();
		author=StringUtils.substringBetween(authorStr, "来源："," ");
		if(StringUtils.isBlank(author)){
			author=StringUtils.substringAfter(authorStr, "来源：");
		}

		if(title==null || title.trim().length()==0){
		}
		date=DateUtils.matchDate(dateStr);
		news.setTitle(StringUtils.trimSpace(title));
		news.setContent(content);
		news.setAuthor(author);
		news.setDate(date);	
		/**
		 * 解析用于更新的地址
		 */
		String updateUrl=null;
			
		return news;
	}
	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}
	public static void main(String[] args) {
		EmoneyNewsAnalyse a=new EmoneyNewsAnalyse();
		String url="http://news.emoney.cn/yaowen/4712767.shtml";
		String fromatUrl=UrlArgumentTop.FromatUrl(url);
		System.out.println("url="+fromatUrl);
		System.out.println(a.isDetailPage(fromatUrl));
		UrlMeta meta=CrawlHTML.responseToURL(fromatUrl);
		NewsMeta parserHtml=a.parserHtml(meta);
		System.out.println(parserHtml);
	}
	
	public boolean isNeedUpdate(){
		return false;
	}
}
